package com.hkd.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hkd.common.core.constants.Constants;
import com.hkd.common.core.constants.HttpConstants;

import com.hkd.common.core.utils.ThreadLocalUtil;
import com.hkd.common.security.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.jta.JtaAfterCompletionSynchronization;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;//从哪个服务配置取，取决于bean交给了哪个服务的Spring管理

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = getToken(request);//请求头中获取token
        if(StrUtil.isEmpty(token)){
//            response.sendError(ResultCode.FAILED_TOKEN_NULL.getCode(), ResultCode.FAILED_TOKEN_NULL.getMessage());
//            log.warn(ResultCode.FAILED_TOKEN_NULL.getMessage());
            return true;
        }

        //存入ThreadLocal中 userID
        Long userId = tokenService.getUserIdFT(token,secret);
        ThreadLocalUtil.set(Constants.USER_ID,userId);

        tokenService.extendToken(token,secret);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       //防止内存泄漏，清除ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        if(StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)){
            token = token.replaceFirst(HttpConstants.PREFIX,"");
        }
        return token;
    }
}
